require File.dirname(__FILE__) + '/asset_tag_helper'



module SimpleUjs
  module Helpers
    module UjsHelper
      include ActionView::Helpers::JavascriptHelper
      include SimpleUjs::Helpers::AssetTagHelper
      
      def convert_options_to_ujs(html_options, options ={})
        if convert_options_to_javascript_with_ujs!(html_options, options) || html_options.keys.grep(/^on/)
          html_options["id"] ||= create_ujs_id if html_options.keys.grep(/^on/).find{|key| html_options[key]}
          html_options.keys.grep(/^on/).each do |key|
            create_ujs_handler(html_options["id"], key.downcase.sub(/^on/, ''), html_options.delete(key)) if html_options[key]
          end
        end if html_options
        nil
      end

      def create_ujs_id
        "ujs_#{rand.to_s.match(/(\d\d+)/).captures.first}"
      end

      def create_ujs_handler(id, evt, javascript, options = {})
        return nil unless should_use_ujs?
        options = {:stop_event => true}.merge(options)
        opt = options[:stop_event] ? 'Event.stop(e); ' : ''
        add_to_ujs_handler_list("Event.observe('#{id}', '#{evt}', function(e){#{opt}#{javascript}});")
      end
      
      def add_to_ujs_handler_list(content)
        @ujs_handlers_list ||= []
        @ujs_handlers_list << content
      end
      
      def flush_ujs_handlers_list(path = {}, session_id = nil)
        return nil unless should_use_ujs?
        session[session_id || :ujs_script] = @ujs_handlers_list.join("\n") if @ujs_handlers_list
        path = "/javascripts/ujs_handler" if !path || path.empty?
        path = url_for(path) if path.is_a?(Hash)
        scripts = []
        scripts << @javascript_include_tags 
        scripts << content_tag("script", "", { "type" => "text/javascript", "src" => path }) if @ujs_handlers_list
        @ujs_handlers_list = nil
        scripts.compact.join("\n")
      end
      
      private
        def convert_options_to_javascript_with_ujs!(html_options, options = {})
          confirm, popup = html_options.delete("confirm"), html_options.delete("popup")

          # post is deprecated, but if its specified and method is not, assume that method = :post
          method = options[:keep_method] ? nil : html_options.delete("method") 
          post   = html_options.delete("post")
          
          if !method && post
            ActiveSupport::Deprecation.warn(
              "Passing :post as a link modifier is deprecated. " +
              "Use :method => \"post\" instead. :post will be removed in Rails 2.0."
            )
            method = :post
          end

          html_options["onclick"] = case
            when popup && method == :post
              raise ActionView::ActionViewError, "You can't use :popup and :post in the same link"
            when confirm && popup
              "if (#{confirm_javascript_function(confirm)}) { #{popup_javascript_function(popup)} };return false;"
            when confirm && method
              "if (#{confirm_javascript_function(confirm)}) { #{method_javascript_function(method)} };return false;"
            when confirm
              "if(#{confirm_javascript_function(confirm)}){document.location = this.href;}"
            when method
              "#{method_javascript_function(method)}return false;"
            when popup
              popup_javascript_function(popup) + 'return false;'
            else
              html_options["onclick"]
          end
          html_options["onclick"] = html_options["onclick"] ? html_options["onclick"] : nil
        end
        
        # def javascript_to_ujs_friendly(javascript)
        #   javascript = javascript.gsub(/this\./im, 'Event.element(e).')
        #   javascript = javascript.gsub(/Form.serialize\(this\)/im, 'Form.serialize(Event.element(e))')
        #   javascript
        # end
        
        alias_method :javascript_tag_without_ujs, :javascript_tag
        def javascript_tag(content, html_options = {})
          add_to_ujs_handler_list(content) and return nil if should_use_ujs?
          javascript_tag_without_ujs(content, html_options)
        end
        
        def should_use_ujs?
          SimpleUjs::Base.use_ujs && !@request.xhr?
        end
        
      
  
    end
  end
end